package com.coders.android.taxi;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.coders.android.R;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class TaxiMapActivity extends FragmentActivity implements LocationListener {

	private final String TAG = this.getClass().getSimpleName();
	private static final int DELAY = 10000;
	private String IMEI;	
	
	private GoogleMap googleMap;
	private Marker marker;
	private double latitude;
	private double longitude;
	
	private UpdateLocationService updateLocationService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_taxi_map);
		
		initComponents();
	}
	
	private void initComponents() {
		
		googleMap = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.taxi_map ) ).getMap();
		
		googleMap.setMapType( GoogleMap.MAP_TYPE_NORMAL );
		googleMap.setMyLocationEnabled( true );

		LocationManager locationManager = null;
		locationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
		
		Location location = null;
		if( locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
			 location = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER );
		else if( locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) )
			 location = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
		else return;
		
		/*googleMap.addMarker( new MarkerOptions().position( gpsLatLng ) );
		googleMap.addMarker( new MarkerOptions().position( wifiLatLng ) );*/
		
		googleMap.animateCamera( CameraUpdateFactory.newLatLngZoom( new LatLng( location.getLatitude(), location.getLongitude() ), 16 ) );
		
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService( Context.TELEPHONY_SERVICE );
		IMEI = telephonyManager.getDeviceId();
		
		updateLocationService = new UpdateLocationService();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.taxi_map, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch( item.getItemId() ) {

			case R.id.taxi_start_service:
				startService( new Intent( this, UpdateLocationService.class ) ); break;
			case R.id.taxi_stop_service:
				stopService( new Intent( this, UpdateLocationService.class ) ); break;
		}
		return true;
	}	
	
	@Override
	public void onLocationChanged(Location arg0) {
		
		if( marker != null )
            marker.remove();
		
		latitude = arg0.getLatitude();
		longitude = arg0.getLongitude();
		
		LatLng latLng = new LatLng( latitude, longitude );
		
		marker = googleMap.addMarker( new MarkerOptions().position( latLng ) );
		
		googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
		googleMap.animateCamera( CameraUpdateFactory.zoomTo( 16 ) );
	}
	
	public class UpdateLocationService extends Service {
		
		private boolean runFlag = false;
		private Updater updater;
		
		@Override
		public void onCreate() {
			super.onCreate();
			this.updater = new Updater();
		}

		@Override
		public int onStartCommand(Intent intent, int flags, int startId) {
			super.onStartCommand(intent, flags, startId);
			
			this.runFlag = true;
			this.updater.start();
			
			return START_STICKY;
		}
		
		@Override
		public void onDestroy() {
			super.onDestroy();
			
			this.runFlag = false;
			this.updater.interrupt();
			this.updater = null;
		}

		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
	}
	
	private class Updater extends Thread {

		HttpClient httpClient = null;
		HttpPost httpPost = null;
		HttpResponse httpResponse = null;		
		
		@Override
		public void run() {
			
			while( updateLocationService.runFlag ) {
				try {
					
					httpClient = new DefaultHttpClient();
					httpPost = new HttpPost( "url del servicio web" );
					httpPost.setHeader( "content-type", "application/json" );
					
					JSONObject jsonObject = new JSONObject();
					
					jsonObject.put( "imei", IMEI );
					jsonObject.put( "latitude", latitude );
					jsonObject.put( "longitude", longitude );
					
					StringEntity stringEntity = new StringEntity( jsonObject.toString() );
					
					httpPost.setEntity( stringEntity );
					
					httpResponse = httpClient.execute( httpPost );
					
					String response = EntityUtils.toString( httpResponse.getEntity() );
					if( !response.equals( "true" ) )
						Log.e( TAG, "FAIL" );
					
					Thread.sleep( DELAY );
					
				} catch (InterruptedException e) {
					updateLocationService.runFlag = false;
				} catch (ParseException e) {
				} catch (IOException e) {
				} catch (JSONException e) {
				}
			}
		}
	}
}
